package logic

import (
	"8-dshop/cache"
	"8-dshop/models"
	"context"
	"errors"

	"8-dshop/shoprpc/internal/svc"
	"8-dshop/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CarAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCarAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CarAddLogic {
	return &CarAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CarAddLogic) CarAdd(in *shoprpc.CarAddRequest) (*shoprpc.CarAddResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	if err := user.FindUserById(models.DB, in.UserId); err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	var product models.Product

	if err := product.FindProductById(models.DB, in.ProductId); err != nil {
		return nil, err
	}
	if product.ID == 0 {
		return nil, errors.New("商品不存在")
	}
	exists, err := cache.FindCartProductExists(in.UserId, in.ProductId)
	if err != nil {
		return nil, err
	}
	if exists == 0 {
		mapData := map[string]interface{}{
			"productId": in.ProductId,
			"userId":    in.UserId,
			"number":    in.Number,
			"title":     product.Title,
			"price":     product.Price,
			"image":     product.Image,
			"info":      product.Info,
		}
		if err = cache.CarAdd(in.UserId, in.ProductId, mapData); err != nil {
			return nil, errors.New("购物车添加失败")
		}
	} else {
		if err = cache.UpdateCartProductNumber(in.UserId, in.ProductId, in.Number); err != nil {
			return nil, err
		}
	}
	return &shoprpc.CarAddResponse{
		ProductId: int64(product.ID),
	}, nil
}
